<template>
  <view class="leave-add-container">
    <view class="page-header">
      <text class="page-title">新增请假申请</text>
      <text class="page-subtitle">提交新的请假申请</text>
    </view>

    <view class="form-container">
      <view class="form-section">
        <text class="section-title">申请信息</text>
        
        <view class="form-item">
          <text class="form-label required">申请人</text>
          <picker 
            :range="userOptions" 
            range-key="display_name" 
            :value="selectedUserIndex"
            @change="onUserChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedUserDisplay || '请选择申请人' }}</text>
            </view>
          </picker>
          <text v-if="errors.requester_id" class="error-text">{{ errors.requester_id }}</text>
          <text class="form-hint">选择提交请假申请的员工</text>
        </view>

        <view class="form-item">
          <text class="form-label required">请假类型</text>
          <radio-group @change="onLeaveTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.leave_type === 1" color="#007aff"/>
              <text class="radio-text">病假</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.leave_type === 2" color="#007aff"/>
              <text class="radio-text">年假</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.leave_type === 3" color="#007aff"/>
              <text class="radio-text">事假</text>
            </label>
            <label class="radio-item">
              <radio value="4" :checked="formData.leave_type === 4" color="#007aff"/>
              <text class="radio-text">其他</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label required">开始日期</text>
          <picker mode="date" :value="formData.start_date" @change="onStartDateChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.start_date || '请选择开始日期' }}</text>
            </view>
          </picker>
          <text v-if="errors.start_date" class="error-text">{{ errors.start_date }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">结束日期</text>
          <picker mode="date" :value="formData.end_date" @change="onEndDateChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.end_date || '请选择结束日期' }}</text>
            </view>
          </picker>
          <text v-if="errors.end_date" class="error-text">{{ errors.end_date }}</text>
        </view>

        <view class="form-item" v-if="formData.start_date && formData.end_date">
          <text class="form-label">请假天数</text>
          <view class="calculated-value">
            <text class="value-text">{{ calculatedDays }}</text>
            <text class="value-unit">天</text>
          </view>
        </view>

        <view class="form-item">
          <text class="form-label required">请假原因</text>
          <textarea 
            v-model="formData.reason" 
            class="form-textarea" 
            placeholder="请输入请假原因"
            maxlength="500"
          />
          <text v-if="errors.reason" class="error-text">{{ errors.reason }}</text>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">提交</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const userOptions = ref([])
const selectedUserIndex = ref(-1)

const formData = reactive({
  requester_id: '',
  leave_type: 1,
  start_date: '',
  end_date: '',
  duration_days: 0,
  reason: '',
  status: 1
})

const errors = reactive({
  requester_id: '',
  start_date: '',
  end_date: '',
  reason: ''
})

const selectedUserDisplay = computed(() => {
  if (selectedUserIndex.value >= 0 && userOptions.value[selectedUserIndex.value]) {
    return userOptions.value[selectedUserIndex.value].display_name
  }
  return ''
})

const calculatedDays = computed(() => {
  if (!formData.start_date || !formData.end_date) return 0
  const start = new Date(formData.start_date)
  const end = new Date(formData.end_date)
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
  formData.duration_days = diffDays
  return diffDays
})

onMounted(async () => {
  await loadUsersFromCloud()  // 使用云对象方法替代直接数据库查询
})

async function loadUsers() {
  try {
    uni.showLoading({ title: '加载员工列表...' })
    
    const db = uniCloud.database()
    const _ = db.command
    
    // 查询所有用户，然后在前端过滤（更兼容的方式）
    const usersRes = await db.collection('uni-id-users')
      .field({
        _id: true,
        username: true,
        nickname: true,
        realname_auth: true,
        mobile: true,
        role: true
      })
      .limit(500)
      .get()
    
    uni.hideLoading()
    
    // 获取实际数据（兼容不同的返回格式）
    const userData = usersRes.result?.data || usersRes.data || []
    
    // 检查查询结果
    if (!Array.isArray(userData)) {
      console.error('查询结果格式错误:', usersRes)
      uni.showToast({
        title: '查询员工列表失败',
        icon: 'none'
      })
      return
    }
    
    // 过滤出需要请假的用户（医生、护士、员工等，不包括纯系统角色admin/manager）
    const staffRoles = ['doctor', 'nurse', 'head_nurse', 'staff', 'director', 'vice_director', 'administrative', 'finance', 'purchaser']
    const filteredUsers = userData.filter(user => {
      const roles = Array.isArray(user.role) ? user.role : (user.role ? [user.role] : [])
      return roles.some(role => staffRoles.includes(role))
    })
    
    // 格式化用户数据
    userOptions.value = filteredUsers.map(user => {
      let displayName = ''
      if (user.realname_auth && user.realname_auth.real_name) {
        displayName = user.realname_auth.real_name
      } else if (user.nickname) {
        displayName = user.nickname
      } else if (user.username) {
        displayName = user.username
      } else if (user.mobile) {
        displayName = user.mobile
      } else {
        displayName = user._id
      }
      
      // 获取角色信息并转换为中文（不包括纯系统角色admin/manager）
      const roleMap = {
        'doctor': '医生',
        'nurse': '护士',
        'head_nurse': '护士长',
        'staff': '员工',
        'director': '院长',
        'vice_director': '副院长',
        'administrative': '行政',
        'finance': '财务',
        'purchaser': '采购员',
        'patient': '患者'
      }
      
      let roles = user.role || []
      if (!Array.isArray(roles)) {
        roles = [roles]
      }
      
      // 如果同时有护士长和护士，只显示护士长
      const hasHeadNurse = roles.includes('head_nurse')
      
      const roleTexts = roles
        .filter(r => r !== 'user' && r !== 'staff')  // 过滤掉user和staff
        .filter(r => !(r === 'nurse' && hasHeadNurse))  // 如果有护士长，过滤掉护士
        .map(r => roleMap[r] || r)
      
      // 如果有其他角色就显示角色，否则不显示括号
      const displayWithRole = roleTexts.length > 0 ? `${displayName} (${roleTexts.join(', ')})` : displayName
      
      return {
        _id: user._id,
        display_name: displayWithRole,
        username: user.username,
        nickname: user.nickname,
        mobile: user.mobile
      }
    })
    
    if (userOptions.value.length === 0) {
      uni.showToast({
        title: '没有可用的员工',
        icon: 'none',
        duration: 3000
      })
    }
  } catch (err) {
    uni.hideLoading()
    console.error('加载员工列表失败:', err)
    uni.showToast({ 
      title: '加载员工列表失败：' + (err.message || '未知错误'), 
      icon: 'none' 
    })
  }
}

// 使用请假云对象的方法
async function loadUsersFromCloud() {
  try {
    uni.showLoading({ title: '加载员工列表...' })
    
    // 调用请假云对象方法查询可请假员工列表（云函数内部调用公共模块）
    const leaveRequestsObj = uniCloud.importObject('dh-leave_requests')
    const result = await leaveRequestsObj.getLeaveEligibleStaff('with_role')
    
    uni.hideLoading()
    
    if (result.code === 200 && result.data) {
      // 格式化数据以匹配原有的数据结构
      userOptions.value = result.data.map(user => ({
        _id: user._id,
        display_name: user.displayName,
        username: '',
        nickname: '',
        mobile: ''
      }))
      
      if (userOptions.value.length === 0) {
        uni.showToast({
          title: '未找到可请假的员工',
          icon: 'none'
        })
      }
    } else {
      console.error('查询员工列表失败:', result.message)
      uni.showToast({
        title: result.message || '查询员工列表失败',
        icon: 'none'
      })
    }
    
  } catch (error) {
    uni.hideLoading()
    console.error('加载员工列表失败:', error)
    uni.showToast({ 
      title: error.message || '加载员工列表失败', 
      icon: 'none' 
    })
  }
}

function onUserChange(e) {
  selectedUserIndex.value = parseInt(e.detail.value)
  if (selectedUserIndex.value >= 0 && userOptions.value[selectedUserIndex.value]) {
    formData.requester_id = userOptions.value[selectedUserIndex.value]._id
    errors.requester_id = ''
  } else {
    formData.requester_id = ''
  }
}

function onLeaveTypeChange(e) {
  formData.leave_type = parseInt(e.detail.value)
}

function onStartDateChange(e) {
  formData.start_date = e.detail.value
  errors.start_date = ''
}

function onEndDateChange(e) {
  formData.end_date = e.detail.value
  errors.end_date = ''
}

function validateForm() {
  let isValid = true
  
  if (!formData.requester_id || formData.requester_id.trim().length === 0) {
    errors.requester_id = '请选择申请人'
    isValid = false
  } else {
    errors.requester_id = ''
  }
  
  if (!formData.start_date) {
    errors.start_date = '请选择开始日期'
    isValid = false
  } else {
    errors.start_date = ''
  }
  
  if (!formData.end_date) {
    errors.end_date = '请选择结束日期'
    isValid = false
  } else {
    errors.end_date = ''
  }
  
  if (formData.start_date && formData.end_date && new Date(formData.start_date) > new Date(formData.end_date)) {
    errors.end_date = '结束日期不能早于开始日期'
    isValid = false
  }
  
  if (!formData.reason || formData.reason.trim().length === 0) {
    errors.reason = '请输入请假原因'
    isValid = false
  } else {
    errors.reason = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '提交中...' })
    
    const submitData = {
      ...formData
    }
    
    // 调用云对象方法创建请假申请（会自动挂载 hospital_id）
    const leaveRequestsObj = uniCloud.importObject('dh-leave_requests')
    const result = await leaveRequestsObj.createLeaveRequest(submitData)
    
    uni.hideLoading()
    
    if (result.code === 201 && result.data && result.data._id) {
      uni.showToast({ title: result.message || '提交成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/leave_requests/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '提交失败', icon: 'none' })
    }
  } catch (err) {
    console.error('提交失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '提交失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/leave_requests/list' })
}
</script>

<style lang="scss" scoped>
.leave-add-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.calculated-value {
  display: flex;
  align-items: baseline;
  padding: 20rpx;
  background: #e3f2fd;
  border-radius: 8rpx;
}

.value-text {
  font-size: 48rpx;
  font-weight: bold;
  color: #1976d2;
  margin-right: 12rpx;
}

.value-unit {
  font-size: 28rpx;
  color: #1976d2;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
